package com.example.window;

import com.example.bean.WaterSenSorFunction;
import com.example.bean.WaterSensor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.DateFormat;

/**
 * Created with IntelliJ IDEA.
 * ClassName: WindowRdeuceDemo
 * Package: com.example.window
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-19
 * Time: 17:41
 */

public class WindowProcessDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> data = env.socketTextStream("hadoop102", 7777)
                .map(new WaterSenSorFunction());

        KeyedStream<WaterSensor, String> sensorKS = data.keyBy(value -> value.getId());

        //1.窗口 增量聚合函数 规约聚合 Reduce
        //1.窗口分配器
        //滚动窗口
        WindowedStream<WaterSensor, String, TimeWindow> sensorWS =
                sensorKS.window(TumblingProcessingTimeWindows.of(Time.seconds(10)));

        //全窗口 来一条数据 存起来 到窗口触发在全部统一计算 提供了上下文信息
        final SingleOutputStreamOperator<String> process = sensorWS.process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
            /**
             * 全窗口计算逻辑 窗口触发时候才会被调用一次
             * @param s 分组的key
             * @param context 上下文
             * @param elements 存的数据
             * @param out 采集器
             * @throws Exception
             */
            @Override
            public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                //上下文 可以获取窗口的一些信息 启停时间
                long start = context.window().getStart();
                long end = context.window().getEnd();
                //格式准换
                String sW = DateFormatUtils.format(start, "yyy-MM-dd HH:mm:ss.SSS");
                String eW = DateFormatUtils.format(end, "yyy-MM-dd HH:mm:ss.SSS");

                //答应集合数量
                long l = elements.spliterator().estimateSize();

                out.collect("key=" + s + "的窗口[" + sW + "," + eW + "] 包含" + l + "条数据 ===> " + elements.toString());


            }
        });
        process.print();


        env.execute();
    }

}
